package com.xyy.saas.payment.util;

import com.xyy.saas.common.util.CommonHttpClientUtil;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.config.RequestConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wuqiongda
 * @Date: 2019/11/12 14:58
 */
public class HttpClientUtil {
    private static String CONNECTION_TIMEOUT = "http.connectTimeout";
    private static String SOCKET_TIMEOUT = "http.socketTimeout";
    private static String REQUEST_TIMEOUT = "http.requestTimeout";
    private static String TOTAL_POOL = "http.totalPool";
    public static int MAX_CONNECTION_TIMEOUT = Integer.parseInt(ApolloUtil.getProperty(CONNECTION_TIMEOUT));
    public static int MAX_SOCKET_TIMEOUT = Integer.parseInt(ApolloUtil.getProperty(SOCKET_TIMEOUT));
    public static int RequestTimeout = Integer.parseInt(ApolloUtil.getProperty(REQUEST_TIMEOUT));

    private static RequestConfig requestConfig;

    private static RequestConfig.Builder configBuilder = RequestConfig.custom();

    static {
        // 设置连接超时
        configBuilder.setConnectTimeout(MAX_CONNECTION_TIMEOUT);
        // 设置读取超时
        configBuilder.setSocketTimeout(MAX_SOCKET_TIMEOUT);
        // 设置从连接池获取连接实例的超时
        configBuilder.setConnectionRequestTimeout(RequestTimeout);
        requestConfig = configBuilder.build();
    }

    private static Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String xyyHttpGetRequest(String url, Map<String, Object> params, Map<String, String> headerMap) throws Exception {
        return CommonHttpClientUtil.httpGet(url, params, headerMap);
    }

    public static String xyyHttpPostRequest(String url,String json, String contentType) throws Exception {
        Map<String, String> headerMap = new HashMap<>(5);
        headerMap.put("content-encoding","UTF-8");
        headerMap.put("content-type", contentType);
        return CommonHttpClientUtil.httpPost(url, json, headerMap, requestConfig);
    }

    public static String xyyHttpPostRequest(String url,String json, String contentType, Map<String, String> header) throws Exception {
        Map<String, String> headerMap = new HashMap<>(5);
        headerMap.put("content-encoding","UTF-8");
        headerMap.put("content-type", contentType);
        headerMap.putAll(header);

        try {
            return CommonHttpClientUtil.httpPost(url, json, headerMap, requestConfig);
        }
        // NoHttpResponseException 重试一次
        catch(NoHttpResponseException ex) {
            LOGGER.warn("Retry due to NoHttpResponseException#xyyHttpPostRequest2:" + ex.getMessage(), ex);
            return CommonHttpClientUtil.httpPost(url, json, headerMap, requestConfig);
        }
    }
}
